package com.fantastic.common.utils;

import com.fantastic.common.exception.AuthException;
import com.fantastic.common.exception.enums.RespStatusInfo;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: rxx
 * @since: 2024/6/14 15:29
 * @description: 响应工具类
 */
public class RespUtil {

    /**
     * 将Token添加到响应头中
     * @param key map的键
     * @param value map的值
     * @param timeout token过期时间
     * @param response 响应对象
     */
    public static void addToken(String key, Object value, long timeout, HttpServletResponse response) {
        try {
            //创建一个Map
            Map<String, Object> map = new HashMap<>();
            map.put(key, value);
            //创建Token
            String jwt = JwtUtils.createToken(map, timeout);
            //添加到响应头中
            response.addHeader("token", jwt);
        } catch (Exception e) {
            //出现异常进行异常重抛，统一抛出服务器异常
            throw new AuthException(RespStatusInfo.SERVER_ERROR);
        }
    }
}
